package com.lxd.mq;

import com.lxd.common.constants.RabbitMQConstants;
import com.lxd.common.model.StandardSubmit;

import com.lxd.feign.cacheClient;
import com.lxd.filter.CheckFilterContext;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author Dongdong
 * @注释
 */

@Component
@Slf4j
public class PreSendListener {
    @Autowired
    private cacheClient client;
    @Autowired
    private CheckFilterContext context;
    @RabbitListener(queues = RabbitMQConstants.SMS_PRE_SEND)
    public void listen(StandardSubmit submit, Message message, Channel channel) throws IOException {
        log.info("【策略模块-接收消息】接收到接口模块的消息submit={}",submit);

        //1、提取出分布式Id
        Long Id = submit.getSequenceId();
        //2、将消息设置状态0，表示正在处理
        boolean flag = client.setNx(Id.toString(), "0", 30l);
        log.info("【策略模块-接收消息】 该消息正在处理");
        if (flag){
            //3、处理消息
            context.check(submit);
            log.info("【策略模块-接收消息】已经手动ack");

            //4、将消息状态改为1，表示处理完毕
            client.set(Id.toString(),"1");
            log.info("【策略模块-接收消息】 该消息处理完毕");

            //5、确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            //3、进入else，说明发生重复消费！

            String value = String.valueOf(client.get(Id.toString()));
            //4、判断该消息的状态是什么，如果为1说明该消息已经处理完毕
            if ("1".equals(value)){
                log.info("【策略模块-接收消息】 该消息发生重复消费，且已经被处理过");
                //5、确认消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                log.info("【策略模块-接收消息】已经手动ack");
            }
        }
    }
}
